import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.filechooser.FileFilter;
import java.util.StringTokenizer;

//import java.awt.*;
//import java.awt.event.MouseEvent;
//import java.awt.event.MouseListener;
//import java.awt.event.KeyListener;
//import java.awt.event.KeyEvent;
import java.util.ArrayList;
//import java.awt.BorderLayout;
//import javax.swing.border.*;
//import java.awt.Color;
//import java.awt.Graphics;
//import java.awt.Graphics2D;

// This class creates the main screen for the data visualization application
@SuppressWarnings("serial")
public class MainGUI extends JFrame {
	
	// Main will make a new instance of the MainGUI class
	public static void main(String[] args){
		new MainGUI();
	}
	
	// Declare frame and panel components
	JFrame mainFrame, studentFrame, numAxesFrame;
	JPanel mainPanel, buttonPanel, stuffPanel, imagePanel, studentCBPanel, mainStudentPanel, visualizeButtonPanel, visualPanel, axisPanel, legendPanel;
	JMenuBar menuBar;
	JMenu fileMenu, editMenu, helpMenu, viewMenu, settingsMenu,numAxesMenu, savesubMenu;
	JMenuItem saveItem, openItem, exitItem, jpgOption, editItem, studentDataItem,axes2Item,axes3Item,axes4Item, onlineHelpItem;
	JLabel introMessage, studentInfoMessage, graphTitle;
	JButton openBrowse, viewButton, visualizeButton;
	JComboBox studentCB, numAxesBox, xBox, yBox, sizeBox, colorBox;;
	JTextArea studentTA;
	GraphPanel graph;
	JCheckBoxMenuItem previousCB;
	JTextField statusbar;
	String status = "Status: ";
	String newstatus = "";
	
	Student selectedStudent;
	
	File file;
	
	String s;
	String selectedFilePath;
	String onlineHelpURL = "index.html";
	//The parent directory of the previous file selected
	String directory = null;
	
	// Variables for reading in student data
	ArrayList<Student> student_data;
	
	String[][] studentData;
	BufferedReader buffRead;
 
	// Constructor for the MainGUI class
	public MainGUI(){
	    // Add frame properties
		mainFrame = new JFrame();
		mainFrame.setTitle("Data Visualization");
		mainFrame.setLocation(300,10);
		mainFrame.setSize(1050,750);	
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.setVisible(true);
		mainFrame.setResizable(true);		
		
		// Add the menu bar	
		mainFrame.setJMenuBar(CreateMenuBar());	
		
		mainFrame.setLayout(new BorderLayout());
		
		mainFrame.add(CreateMainPanel(), BorderLayout.NORTH);
		mainFrame.add(CreateGraphPanel(), BorderLayout.CENTER);
		
		statusbar = new JTextField(status);
		statusbar.setEditable(false);
		mainFrame.add(statusbar, BorderLayout.PAGE_END);
		mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });			
	}
	
	public JPanel CreateMainPanel(){
		mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		
		mainPanel.add(LoadImage(), BorderLayout.WEST);
		mainPanel.add(CreateStuff(), BorderLayout.CENTER);
				
		return mainPanel;
	}
	
	public JPanel CreateOpenButtonPanel(){
		buttonPanel = new JPanel();						
		openBrowse = new JButton("Browse for Data Set");
		openBrowse.setToolTipText("Open a CSV file data set");
		buttonPanel.add(openBrowse);		
		openBrowse.addActionListener(new ClickedBrowse());		
		return buttonPanel;
	}
	
	public JPanel CreateGraphPanel(){
		graph = new GraphPanel(500,500);
		visualPanel = new JPanel();
		graphTitle = new JLabel("No Graph");
		graphTitle.setAlignmentX(JLabel.CENTER);
		visualPanel.setLayout(new BorderLayout());
		visualPanel.add(graph, BorderLayout.CENTER);
		visualPanel.add(createAxisPanel(), BorderLayout.EAST);
		visualPanel.add(createLegendPanel(), BorderLayout.WEST);
		return visualPanel;
	}
	
	private JPanel createAxisPanel(){
		numAxesBox=createNumAxesCB();
		xBox = createAxisCB();
		yBox = createAxisCB();
		sizeBox = createAxisCB();
		colorBox = createAxisCB();
		axisPanel = new JPanel();
		GridLayout layout = new GridLayout(7,2);
		layout.setVgap(60);
		axisPanel.setLayout(layout);
		numAxesBox.setEnabled(false);
		xBox.setEnabled(false);
		yBox.setEnabled(false);
		sizeBox.setEnabled(false);
		colorBox.setEnabled(false);
		axisPanel.add(new JLabel("Num Axes"));
		axisPanel.add(numAxesBox);
		axisPanel.add(new JLabel("X-Axis"));
		axisPanel.add(xBox);
		axisPanel.add(new JLabel("Y-Axis"));
		axisPanel.add(yBox);
		axisPanel.add(new JLabel("Point color"));
		axisPanel.add(colorBox);
		axisPanel.add(new JLabel("Point size"));
		axisPanel.add(sizeBox);
		sizeBox.setVisible(false);
		colorBox.setVisible(false);
		axisPanel.getComponent(6).setVisible(false);
		axisPanel.getComponent(8).setVisible(false);
		return axisPanel;
	}
	
	public JComboBox createNumAxesCB(){
		JComboBox tempBox = new JComboBox();
		tempBox.addItem("2");
		tempBox.addItem("3");
		tempBox.addItem("4");
		tempBox.addItemListener(new NumAxesChanged());
		return tempBox;
	}
	
	public JPanel createLegendPanel(){
		legendPanel = new JPanel();
		legendPanel.setLayout(new GridLayout(4,1));
		String axisLabels[] = {"X-Axis", "Y-Axis", "Point Color", "Point Size"};
		for(int i = 0; i < 4; i++){
			JPanel aPanel = new JPanel();
			aPanel.setLayout(new GridLayout(10,2));
			JLabel aLabel = new JLabel(axisLabels[i]);
			aPanel.add(aLabel);
			for(int j = 0; j < 19; j++){
				JLabel label = new JLabel("");
				aPanel.add(label);
			}
			legendPanel.add(aPanel);
		}
		return legendPanel;
	}
	
	public JComboBox createAxisCB(){
		JComboBox axisBox = new JComboBox();
		axisBox.addItem("Age");
		axisBox.addItem("GPA");
		axisBox.addItem("Year");
		axisBox.addItem("Major");
		axisBox.addItem("Height");
		axisBox.addItem("Weight");
		axisBox.addItem("Avg Credit Hours");
		axisBox.addItem("Favorite Food");
		axisBox.addItem("# of Absences");
		axisBox.addItem("Employed?");
		axisBox.addItemListener(new AxisChanged());
		return axisBox;
	}
		
	public JPanel CreateStuff(){
		stuffPanel = new JPanel();
		stuffPanel.setLayout(new BorderLayout());
		introMessage = new JLabel("Welcome to DataDiggers! You're one stop shop to visualizing a student data set!");
		
		stuffPanel.add(introMessage, BorderLayout.NORTH);
		stuffPanel.add(CreateOpenButtonPanel(), BorderLayout.CENTER);
		
		return stuffPanel;
		
	}
	// Create the menu bar 
	public JMenuBar CreateMenuBar(){
		menuBar = new JMenuBar();
		
		// Create new menu options
		fileMenu = new JMenu("File");
		editMenu = new JMenu("Edit");
		helpMenu = new JMenu("Help");
		viewMenu = new JMenu("View");
		settingsMenu = new JMenu("Settings");
		numAxesMenu = new JMenu("Number of Axes");
		
		savesubMenu = new JMenu("Save");				
		
		openItem = new JMenuItem("Open");
		openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.ALT_MASK));

		openItem.setToolTipText("Open Previous Visualizations");
		
		jpgOption = new JMenuItem("Save to jpg");
		jpgOption.setToolTipText("Save Current Graph Visualization to jpg file");
		jpgOption.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J, ActionEvent.ALT_MASK));

		savesubMenu.add(jpgOption);
							
		exitItem = new JMenuItem("Exit");
		exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
		
		onlineHelpItem = new JMenuItem("Online Help");
		onlineHelpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.ALT_MASK));

		previousCB = new JCheckBoxMenuItem("Load");
		previousCB.setToolTipText("Load Most Recent Opened Data File");
		previousCB.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));

		
		editItem = new JMenuItem("Edit Database");
		editItem.setToolTipText("Add/Remove Entries in Data Set");
		editItem.setEnabled(false);
		editItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));
		studentDataItem = new JMenuItem("Student Database");
		studentDataItem.setToolTipText("View any Student in the CSV file");
		studentDataItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.ALT_MASK));
		studentDataItem.setEnabled(false);
		axes2Item = new JMenuItem("2 Axes");
		axes2Item.setToolTipText("Set number of attributes on graph to 2");
		axes3Item = new JMenuItem("3 Axes");
		axes3Item.setToolTipText("Set number of attributes on graph to 3");
		axes4Item = new JMenuItem("4 Axes");
		axes4Item.setToolTipText("Set number of attributes on graph to 4");
		
		// Add an action to the exit item
		openItem.addActionListener(new ClickedBrowse());
		exitItem.addActionListener(new ClickedExit());
		previousCB.addActionListener(checkedPreviousCB);

		onlineHelpItem.addActionListener(new ClickedOnlineHelp());
		editItem.addActionListener(new ClickedEdit());
		studentDataItem.addActionListener(new ClickedStudentData());
		axes2Item.addActionListener(new ClickedNumAxes());
		axes3Item.addActionListener(new ClickedNumAxes());
		axes4Item.addActionListener(new ClickedNumAxes());
		
		numAxesMenu.add(axes2Item);
		numAxesMenu.add(axes3Item);
		numAxesMenu.add(axes4Item);
		numAxesMenu.setEnabled(false);
		// Add items to the File menu option
		fileMenu.add(openItem);
		fileMenu.add(savesubMenu);
		fileMenu.add(previousCB);
		fileMenu.add(exitItem);
		helpMenu.add(onlineHelpItem);
		editMenu.add(editItem);
		viewMenu.add(studentDataItem);
		settingsMenu.add(numAxesMenu);
		
		// Add the menu options
		menuBar.add(fileMenu);
		menuBar.add(editMenu);
		menuBar.add(viewMenu);
		menuBar.add(settingsMenu);
		menuBar.add(helpMenu);
		
		return menuBar;
	}
	
	// Action Listener Class for exiting the program
    public class ClickedExit implements ActionListener{
        public void actionPerformed(ActionEvent e){
        	System.exit(EXIT_ON_CLOSE);
        }
    }
    
    public class ClickedOnlineHelp implements ActionListener{
        @SuppressWarnings("static-access")
		public void actionPerformed(ActionEvent e){
        	BrowserControl bc = new BrowserControl();
        	bc.displayURL(onlineHelpURL);
        }
    }
    
    public JPanel CreateStudentCB(){
    	studentCBPanel = new JPanel();
    	studentCB = new JComboBox();
    	studentCB.addItem("");
    	for (int i=0; i<student_data.size(); i++){
			studentCB.addItem(student_data.get(i).getFirst_name()+ " " + student_data.get(i).getLast_name());
		}	
    	studentCB.addItemListener(new StudentChanged());	
		studentCBPanel.add(studentCB);	
    	return studentCBPanel;
    	
    }
    public class ClickedStudentData implements ActionListener{
        public void actionPerformed(ActionEvent e){
        	studentFrame = new JFrame();
        	studentInfoMessage = new JLabel("Select Student to View");
    		studentFrame.setTitle("Student Database");
    		studentFrame.setLocation(400,150);
    		studentFrame.setSize(700,350);	
    		studentFrame.setVisible(true);
    		studentFrame.setResizable(false);		
    		      		
    		studentFrame.setLayout(new BorderLayout());
    		studentFrame.add(CreateMainStudentPanel(), BorderLayout.WEST);
    		
    		studentTA = new JTextArea();
    		studentTA.setEditable(false);
    		studentFrame.add(studentTA, BorderLayout.CENTER);
    		    		
        }
    }
    
    public JPanel CreateMainStudentPanel()
    {
    	mainStudentPanel = new JPanel();
    	mainStudentPanel.setLayout(new BorderLayout());
    	
    	mainStudentPanel.add(studentInfoMessage, BorderLayout.PAGE_START);
    	mainStudentPanel.add(CreateStudentCB(),  BorderLayout.CENTER); 
    	    	
    	return mainStudentPanel;
    }

	public class StudentChanged implements ItemListener{
		public void itemStateChanged(ItemEvent e){
    		String studentInfo = "";
    		selectedStudent = new Student();
        	for (int i=0; i<student_data.size(); i++)
        	{
    			if ((studentCB.getSelectedItem().toString().contains(student_data.get(i).getFirst_name())) && (studentCB.getSelectedItem().toString().contains(student_data.get(i).getLast_name())))
    			{    				
    				selectedStudent = student_data.get(i);
    			}
    		}
        	
        	String employed = "";
        	if (selectedStudent.isIs_employed())
        	{
        		employed = "y";
        	}
        	else
        	{
        		employed = "n";
        	}
        	
        	studentInfo = "First Name: " + selectedStudent.getFirst_name() + "\nLast Name: " + selectedStudent.getLast_name() + "\nAge: " + selectedStudent.getAge() + "\nClass: " + selectedStudent.getClass_year() + "\nMajor: " + selectedStudent.getMajor() + "\nGPA: " + selectedStudent.getGpa() + "\nWeight: " + selectedStudent.getWeight() + "\nHeight: " + selectedStudent.getHeight() + "\nCredit Hour Average: " + selectedStudent.credit_hour_ave + "\nFavorite Food: " + selectedStudent.favorite_food + "\nAbsenses: " + selectedStudent.getAbscences() + "\nEmployed: " + employed;
    		studentTA.setText(studentInfo);
    	}
    }
    
    // Class for browsing for a csv file
    public class ClickedBrowse implements ActionListener{
    	public void actionPerformed(ActionEvent e){    		
			try {
				FileReader inFile = new FileReader("Previous_Directory.txt");
				BufferedReader br = new BufferedReader(inFile);
												
				while((s = br.readLine()) != null) 
				{
					directory = s;					
				}
				inFile.close(); 
				
			} catch (FileNotFoundException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			JFileChooser fc;
    		String filename = File.separator+"tmp";
    		if(directory != null)
    		{
    			fc = new JFileChooser(directory);
    		}
    		else
    		{
    			fc = new JFileChooser(new File(filename));
    		}
    		FileFilter csvFilter = new ExtensionFileFilter(null, new String[] { "CSV" });
    	    fc.addChoosableFileFilter(csvFilter);
    	    
    		int status = fc.showDialog(mainFrame, "Select Data Set");
    		    		    		
    	    if (status == JFileChooser.APPROVE_OPTION)
    	    {
    	    	file = fc.getSelectedFile();
    	    	
    	    	selectedFilePath = fc.getSelectedFile().toString();
    	    	    	                                
	            try {
					FileWriter outFile = new FileWriter("Previous_Directory.txt");
					outFile.write(file.getPath());
					outFile.close();
				} catch (IOException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				
	            if(file.exists()){	            
	            	// Put the file in a buffered reader
	            	try {
						buffRead = new BufferedReader(new FileReader(file));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
					// Initialize the file reading items
					String line = null;
					student_data = new ArrayList<Student>();
				
					// Read each line of the file
					try {
						while((line = buffRead.readLine()) != null){
						
							StringTokenizer st = new StringTokenizer(line,",");
							while(st.hasMoreTokens()){
							
								// Make a new student object and read in each of the attributes from the csv
								Student new_student = new Student();
								new_student.setFirst_name(st.nextToken());
								new_student.setLast_name(st.nextToken());
								new_student.setAge(Integer.parseInt(st.nextToken()));	// Convert 'age' from string to int
								new_student.setClass_year(st.nextToken());
								new_student.setMajor(st.nextToken());
								new_student.setGpa(Double.parseDouble(st.nextToken()));	// Convert 'gpa' from string to double
								new_student.setWeight(Integer.parseInt(st.nextToken()));
								new_student.setHeight(Double.parseDouble(st.nextToken()));
								new_student.setCredit_hour_ave(Double.parseDouble(st.nextToken()));
								new_student.setFavorite_food(st.nextToken());
								new_student.setAbscences(Integer.parseInt(st.nextToken()));
							
								// Set the is_employed bool field
								String is_employed = st.nextToken();
								if (is_employed.charAt(0) == 'y'){
									new_student.setIs_employed(Boolean.valueOf("true"));			
								}
								else{
									new_student.setIs_employed(Boolean.valueOf("false"));
								}
							
								student_data.add(new_student);
								studentDataItem.setEnabled(true);
								editItem.setEnabled(true);
								numAxesMenu.setEnabled(true);
							}
							//Defaults
							numAxesBox.setEnabled(true);
							xBox.setSelectedItem("Age");
							yBox.setSelectedItem("GPA");
							colorBox.setSelectedItem("Height");
							sizeBox.setSelectedItem("Weight");
							setEnabledAxes();
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            }
    	    }
    	}
    }
    
    public class ClickedNumAxes implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		JMenuItem temp = (JMenuItem)e.getSource();
    		switch(temp.getText().charAt(0)){
    		case '2':
    			numAxesBox.setSelectedItem("2");
    			break;
    		case '3':
    			numAxesBox.setSelectedItem("3");
    			break;
    		case '4':
    			numAxesBox.setSelectedItem("4");
    			break;
    		}
    	}
    }
    
    public class NumAxesChanged implements ItemListener{
    	public void itemStateChanged(ItemEvent e){
    		setEnabledAxes();
    	}
    }
    
    public class AxisChanged implements ItemListener{
    	public void itemStateChanged(ItemEvent e){
    		updateGraph();
    	}
    }
 
    public class ClickedEdit implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		String excelPath = "";    		
    		File root = new File("C:\\Program Files\\Microsoft Office\\");
    		String[] extensions = {"EXE","exe"};
    		@SuppressWarnings("rawtypes")
			Collection files = FileUtils.listFiles(root, extensions, true);
    		
    		for (@SuppressWarnings("rawtypes")
			Iterator iterator = files.iterator(); iterator.hasNext();) 
    		{
    			File pfile = (File) iterator.next();
    			if (pfile.getAbsolutePath().contains("EXCEL"))
    			{
    				excelPath = pfile.getAbsolutePath();
    			}
    		}
    		
	    	try { 				    			 			
				@SuppressWarnings("unused")
				Process p = Runtime.getRuntime().exec(excelPath + " " + file.getAbsolutePath());
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
				System.out.println("Cannot find Excel");
			}
    	}   	
    	
    }
    
    //Not sure where the actual gnome image is, so replace in gnome file
    public JPanel LoadImage() {
    	imagePanel = new JPanel();
    	try {
    		BufferedImage image = ImageIO.read(new File("gnome.jpg"));    		    		
    		JLabel pictureLabel = new JLabel(new ImageIcon(image));
    		imagePanel.add(pictureLabel);	    			
       } catch (IOException e) {
    	   System.out.println("Error Finding Image");
       }      		
       
       return imagePanel;
    }
    
    public void setEnabledAxes(){
    	xBox.setEnabled(true);
    	yBox.setEnabled(true);
    	if(numAxesBox.getSelectedItem().equals("3") || numAxesBox.getSelectedItem().equals("4")){
    		axisPanel.getComponent(6).setVisible(true);
    		colorBox.setVisible(true);
    		colorBox.setEnabled(true);
    	}
    	else{
    		axisPanel.getComponent(6).setVisible(false);
    		colorBox.setVisible(false);
    		colorBox.setEnabled(false);
    	}
    	if(numAxesBox.getSelectedItem().equals("4")){
    		axisPanel.getComponent(8).setVisible(true);
    		sizeBox.setEnabled(true);
    		sizeBox.setVisible(true);
    	}
    	else{
    		axisPanel.getComponent(8).setVisible(false);
    		sizeBox.setEnabled(false);
    		sizeBox.setVisible(false);
    	}
    	updateGraph();
    }
    
    public void updateGraph(){
    	ArrayList<String> axisLabels = new ArrayList<String>();
		axisLabels.add(xBox.getSelectedItem().toString());
		axisLabels.add(yBox.getSelectedItem().toString());
		if(colorBox.isEnabled()){
			axisLabels.add(colorBox.getSelectedItem().toString());
		}
		else{
			axisLabels.add("");
		}
		if(sizeBox.isEnabled()){
			axisLabels.add(sizeBox.getSelectedItem().toString());
		}
		else{
			axisLabels.add("");
		}
		graph.drawGraph(student_data, axisLabels);
		updateLegend(graph.getLegend());
		visualPanel.repaint();
		mainFrame.repaint();
    }
    
    public void updateLegend(Legend l){    	
    	ArrayList<ArrayList<String[]>> entries = l.getLegendEntries();
    	for(int i = 0; i < entries.size(); i++){
    		JPanel nextPanel = (JPanel)legendPanel.getComponent(i);
    		for(int j = 0; j < entries.get(i).size(); j++){
    			JLabel kLabel = (JLabel)nextPanel.getComponent(2*j+2);
    			kLabel.setText(entries.get(i).get(j)[0]);
    			JLabel lLabel = (JLabel)nextPanel.getComponent(2*j+3);
    			lLabel.setText(entries.get(i).get(j)[1]);
    			kLabel.repaint();
    			lLabel.repaint();
    		}
    		for(int j = entries.get(i).size(); j < 9; j++){
    			JLabel kLabel = (JLabel)nextPanel.getComponent(2*j+2);
    			kLabel.setText("");
    			JLabel lLabel = (JLabel)nextPanel.getComponent(2*j+3);
    			lLabel.setText("");
    			kLabel.repaint();
    			lLabel.repaint();
    		}
    		nextPanel.repaint();
    	}
    	legendPanel.repaint();
    }
   
    ActionListener checkedPreviousCB = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
        	if (previousCB.isSelected())
        	{        		
        		try {
    				FileReader inFile = new FileReader("Previous_Directory.txt");
    				BufferedReader br = new BufferedReader(inFile);
    												
    				while((s = br.readLine()) != null) 
    				{
    					File tempfile = new File(s);
    					file = tempfile;					
    				}
    				inFile.close(); 
    				
    			} catch (FileNotFoundException e2) {
    				// TODO Auto-generated catch block
    				e2.printStackTrace();
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			} 
    			    	    	    	    	    	                                
	            if(file.exists())
	            {	            
	            	// Put the file in a buffered reader
	            	try {
						buffRead = new BufferedReader(new FileReader(file));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
					// Initialize the file reading items
					String line = null;
					student_data = new ArrayList<Student>();
				
					// Read each line of the file
					try {
						while((line = buffRead.readLine()) != null){
						
							StringTokenizer st = new StringTokenizer(line,",");
							while(st.hasMoreTokens()){
							
								// Make a new student object and read in each of the attributes from the csv
								Student new_student = new Student();
								new_student.setFirst_name(st.nextToken());
								new_student.setLast_name(st.nextToken());
								new_student.setAge(Integer.parseInt(st.nextToken()));	// Convert 'age' from string to int
								new_student.setClass_year(st.nextToken());
								new_student.setMajor(st.nextToken());
								new_student.setGpa(Double.parseDouble(st.nextToken()));	// Convert 'gpa' from string to double
								new_student.setWeight(Integer.parseInt(st.nextToken()));
								new_student.setHeight(Double.parseDouble(st.nextToken()));
								new_student.setCredit_hour_ave(Double.parseDouble(st.nextToken()));
								new_student.setFavorite_food(st.nextToken());
								new_student.setAbscences(Integer.parseInt(st.nextToken()));
							
								// Set the is_employed bool field
								String is_employed = st.nextToken();
								if (is_employed.charAt(0) == 'y'){
									new_student.setIs_employed(Boolean.valueOf("true"));			
								}
								else{
									new_student.setIs_employed(Boolean.valueOf("false"));
								}
							
								student_data.add(new_student);
								studentDataItem.setEnabled(true);
								editItem.setEnabled(true);
								numAxesMenu.setEnabled(true);
							}
							//Defaults
							numAxesBox.setEnabled(true);
							xBox.setSelectedItem("Age");
							yBox.setSelectedItem("GPA");
							colorBox.setSelectedItem("Height");
							sizeBox.setSelectedItem("Weight");
							setEnabledAxes();
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            }
	            else
	            {
	            	newstatus = "Status: Previous Data Set Not Found";
	            	statusbar.setText(newstatus);	            	
	            }
	            	
        }
      }
    };
}